package com.pa.chong.pachong.tool.dowork;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

//@Component
public class ScheduledTest {
    private static final Logger logger = LoggerFactory.getLogger(ScheduledTest.class);

    @Autowired
    private RestTemplate restTemplate;

    private static String href = new String();

//    @Scheduled(cron="0 0/2 * * * ?")
    @Scheduled(cron="0/2 * * * * ? ")
    public void executeFileDownLoadTask() {

        logger.info("------------>task-start");

        task();

        logger.info("------------>task-end");

    }

    @Async
    public void task() {
        String url = "https://www.mzitu.com/all/";
        Document document = null;
        try {
            document = Jsoup.connect(url).timeout(100000).get();
            Elements elements = document.select("[class=archives]").first().select("li").first().select("a");
            String tempHref = elements.first().attr("href");
            String desc = elements.first().text();
            if(!href.equals(tempHref)){
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
                map.add("text",desc);
                map.add("desp",tempHref);

                String res = restTemplate.getForObject("https://sc.ftqq.com/SCU51457T31c56734d13c07c93130b830617ddb6e5cdabc11593d0.send?text={text}&desp={desp}", String.class, map);
                System.out.println(res);

                href = tempHref;
            }else {
                logger.info("---------->图片没有更新");
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
